<?php

namespace App\Jobs;

use App\Model\Messages;
use App\Model\Users;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use WebSocket\Client;

class sendOfflineMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $user_id;
    public $client;
    public $message;
    public $user;
    /**
     * Create a new job instance.
     * @param String $user_id 接受方
     *
     * @return void
     */
    public function __construct($user_id)
    {
        $this->user_id = $user_id;
        $this->client = new Client('ws://127.0.0.1:1024');
//        $this->message = new Messages();
//        $this->user = new Users();
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            $this->message = new Messages();
            $this->user = new Users();
            $msg_list = $this->message->where(['to'=>$this->user_id,'status'=>'0'])->get();

            foreach ($msg_list as $k=>$v) {
                $this->client->send(json_encode([
                    'type'=>'send_to_friend',
                    'friend_id'=>$v->to,
                    'msg'=>$v->content,
                    'from'=>$this->user->find($v->from)->value('user_name')
                ]));
                $v->status = '1';
                $v->save();
            }

            $this->client->close();

        } catch (\Exception $exception)
        {

        }

    }
}
